package com.homestead.aspect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author yhb
 * @date 2021-03-12 21:27
 */

public class RedisMethodInterceptor implements MethodInterceptor {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private Object targetObj;

    public RedisMethodInterceptor(Object targetObj) {
        this.targetObj = targetObj;
    }

    public <V> V getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(targetObj.getClass());

        @SuppressWarnings("unchecked")
        V v = (V) enhancer.create();
        return v;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before(method);
        Object result = methodProxy.invoke(o, args);
        return result;
    }

    private void before(Method method) {
        Class<?> declaringClass = method.getDeclaringClass();
        String target = declaringClass.getName() + "#" + method.getName();
        logger.info("{} start", target);
    }

    private void after(Method method) {
        Class<?> declaringClass = method.getDeclaringClass();
        String target = declaringClass.getName() + "#" + method.getName();
        logger.info("{} end", target);
    }
}
